package com.mamingchao.basic.iterator.v2;

/**
 * Created by mamingchao on 2020/10/19.
 */
public class ArrayList_<E> implements Collection_<E>{

    int index;

    E[] objects = (E[])new Object[10];

    public ArrayList_() {

    }

    @Override
    public void add(E o) {
        if (index >= objects.length) {
            E[] newObjects = (E[])new Object[objects.length*2];
            System.arraycopy(objects,0,newObjects,0,objects.length);
            objects = newObjects;
        }

        objects[index] = o;
        index ++;
    }

    @Override
    public int size() {
        return index;
    }

    @Override
    public void remove(E o) {
        for (int i = 0; i < index; i++) {
            if (o.equals(objects[i])) {
                System.arraycopy(objects,i+1,objects,i,index-i);
                index --;
            }
        }
    }

    @Override
    public E get(int index) {
        return objects[index];
    }

    @Override
    public Iterator_ iterator() {
        return new ArrayListIterator_();
    }



    class ArrayListIterator_ implements Iterator_ {

        int currentIndex;

        @Override
        public boolean hasNext() {
            if (currentIndex < index) return true;
            return false;
        }

        @Override
        public E next() {
            E result =  objects[currentIndex];
            currentIndex ++ ;
            return result;
        }
    }
}



